/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.cxhd.lis.device;

import com.cxhd.lis.util.DateUtil;
import com.cxhd.lis.util.Tool;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @author 52461
 */
public class IMS_972_2 {

    private String baseData;
    private String device_code = "ims-972";
    private String code = "DJ";
    private String sampletype = "血清";
    private String sampletypeId = null;
    private String baseLine = System.getProperty("line.separator");

    public IMS_972_2(String baseData) {
        this.baseData = baseData;
        parseComData();
        // getSampleTypeId();
    }

    public void parseComData() {

        try {
            String sampleNo = null;
            String testDate = DateUtil.getDateEN();

            String testTime = null;
            Map<String, String> resultMap = new HashMap<String, String>();
            System.out.println(baseData);
            String alls[] = baseData.split("\n");
            // System.out.println(alls.length+" ====="+baseData.split("\n").length+" ====="+baseData.split("\r\n").length);
            int n = 0;

            for (int i = 0; i < alls.length; i++) {
                String das[] = alls[i].replaceAll(" +", "@").split("@");
                System.out.println(alls[i]);
                if (das.length > 1) {
                    if (das[0].equalsIgnoreCase("PAT_ID")) {
                        sampleNo = das[1];
                    }
                    resultMap.put(das[0], " " + das[1]);

                }
            }
            sendDb(Tool.getSampleNo(code, sampleNo), testDate, resultMap);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("数据不完整解析错误");
        }

    }

    public void parseResult(String data, Map<String, String> map) {
        if (data.indexOf(" ") > -1) {
            String das[] = data.trim().replaceAll(" +", "@").split("@");

            if (das.length > 0 && das[0].trim().length() > 0) {

                map.put(das[0], " " + das[1]);

            }
        }
    }

    public String getResult(String result) {

        return result.replace("mmol/L", "").replace("g/L", "").replace("umol/L", "").replace("Cells/uL", "");

    }

    public void sendDb(String sampleNo, String datetime, Map<String, String> result) {

        System.out.println(sampleNo + "  " + datetime);
        // System.out.println(result);

        for (String key : result.keySet()) {
            try {
                System.out.println("保存到数据库");
                makeInsertSqlInsert(tranMap(sampleNo, datetime, key, result.get(key)), "lis_testresult");
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }

    }

    //转换数据结构
    public Map<String, String> tranMap(String sampleNo, String datetime, String key, String value) {
        try {
            Map<String, String> newMap = new HashMap<String, String>();

            //Record rs = Db.findFirst("select * from lis_testdescribe where TESTID='" + key.trim().replace("*", "") + "'");
            Record rs = Db.findFirst("select * from pp_device_test where TESTID='" + key.trim().replace("*", "") + "' AND DEVICEID='" + device_code + "'  limit 1");
            if (rs != null) {
                newMap.put("ITEMPK", rs.get("TESTPK") + "");
                newMap.put("TESTID", rs.get("TESTID") + "");
                newMap.put("UNIT", rs.get("UNIT") + "");
                newMap.put("SAMPLENO", sampleNo);

                newMap.put("TESTRESULT", value);
                newMap.put("MEASURETIME", datetime);
                newMap.put("DEVICEID", device_code);
                newMap.put("SAMPLETYPE", "16");
                newMap.put("UUID", Tool.string2MD5(datetime.trim() + sampleNo.trim() + device_code));
                return newMap;

            }
            return null;
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

    //构建sql
    private boolean makeInsertSqlInsert(Map<String, String> map, String tableName) throws Exception {

        if (map == null) {
            return false;
        }

        String sql = "";
        StringBuilder sqlHead = new StringBuilder();
        StringBuilder sqlvalue = new StringBuilder();
        int index = 0;
        String[] values = new String[map.size()];
        sqlHead.append("insert into ").append(tableName).append(" (");
        sqlvalue.append(" values (");
        for (String key : map.keySet()) {
            values[index] = map.get(key);
            index++;
            if (index == map.size()) {
                sqlHead.append("`").append(key).append("`").append(" )");
                sqlvalue.append(map.get(key) == null ? "null)" : "'" + map.get(key) + "')");
                // map.get(key)==null?"":"";
                // sqlvalue.append("? )");
            } else {
                sqlHead.append("`").append(key).append("`").append(" , ");
                sqlvalue.append(map.get(key) == null ? "null," : "'" + map.get(key) + "',");
                //sqlvalue.append("?,");
            }

        }
        sql = sqlHead.append(sqlvalue).toString();
        //System.out.println(sqlHead.append(sqlvalue).toString()+"  "+values.length);
        //logger.info(sql);
        try {
            Db.update(sql);
        } catch (Exception e) {
            System.out.println(e);
        }
        return true;

    }

}
